<template>
<div>
    <div style="display: flex;">
        <el-upload 
        action="#"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="importExcel"><el-button icon="el-icon-upload2">导入 Excel</el-button></el-upload>
        <el-button icon="el-icon-download"  @click="downloadExcel">导出 Excel</el-button>
    </div>
    <div v-loading="loading" 
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)" id="luckysheet" style="margin-top:39px;padding:0px;position:absolute;width:1470px;height:623px;left: 0px;top: 0px;"></div>
    <div class="input-container">
     <el-input v-model="need" type="textarea" style="width:400px;" :rows="4" placeholder="输入内容" />
     <div class="button-container">
        <el-button circle icon="el-icon-video-play" @click="handleExcel"></el-button>
        <el-button circle icon="el-icon-refresh-left" @click="handleBack"></el-button>
    </div>
    </div>
</div>
</template>

<script>
import { exportExcel } from '@/utils/export';
import LuckyExcel from 'luckyexcel'
import { analyseJsonData } from '@/api/ai';

export default {
    name:"ExcelEdit",
    data(){
        return{
            file:null,//用户上传的文件
            loading:false,
            need:"",
            totalRow:0,
            firstRow:0,
            totalCol:0,
            firstCol:0,
        }
    },
    mounted() {
        luckysheet.create({
            container: "luckysheet",
            showinfobar: false,
            showsheetbar: true,
            showtoolbar: true,
            showstatisticbar: true,
            showstatusbar: true,
            showgrid: true,
            showrowheader: true,
            showcolumnheader: true,
            rowheight: 25,
            columnwidth: 100,
            zoom: 100,
            defaultzoom: 100,
            defaultrowheight: 25,
            defaultcolumnwidth: 100,
            lang: 'zh',
            // 更多配置选项...
        });
    },
    methods:{
        importExcel(file,fileList){
            this.file=file.raw
             // 使用 LuckyExcel 转换文件
             LuckyExcel.transformExcelToLucky(
                    this.file,
                    (exportJson) => {
                        console.log(exportJson.sheets)
                        this.totalRow=exportJson.sheets[0].celldata[exportJson.sheets[0].celldata.length-1].r
                        this.totalCol=exportJson.sheets[0].celldata[exportJson.sheets[0].celldata.length-1].c
                        //console.log(this.totalCol)
                        luckysheet.create({
                            container: "luckysheet",
                            showinfobar: false,
                            showsheetbar: true,
                            showtoolbar: true,
                            showstatisticbar: true,
                            showstatusbar: true,
                            showgrid: true,
                            showrowheader: true,
                            showcolumnheader: true,
                            rowheight: 25,
                            columnwidth: 100,
                            zoom: 100,
                            defaultzoom: 100,
                            defaultrowheight: 25,
                            defaultcolumnwidth: 100,
                            lang: 'zh',
                            data:exportJson.sheets
        });
    },
                    (err) => {
                        console.error('Import failed. Is your file a valid xlsx?', err);
                    }
                );
        },
        downloadExcel(){
            exportExcel(luckysheet.getAllSheets(),"下载")
        },
        async handleExcel(){
            if(luckysheet.getAllSheets()[0].celldata.length!=0){
                if(this.need.length!=0){
            this.totalCol=luckysheet.getAllSheets()[0].celldata[luckysheet.getAllSheets()[0].celldata.length-1].c
            this.firstCol=luckysheet.getAllSheets()[0].celldata[0].c
            this.totalRow=luckysheet.getAllSheets()[0].celldata[luckysheet.getAllSheets()[0].celldata.length-1].r
            this.firstRow=luckysheet.getAllSheets()[0].celldata[0].r
            luckysheet.setRangeShow({row:[this.firstRow,this.totalRow],column:[this.firstCol,this.totalCol]})
            this.loading=true
            analyseJsonData({data:{rawData:JSON.stringify(luckysheet.getRangeJson(false)),need:this.need}}).then(response=>{
                this.loading=false
                console.log(response)
                var cleanedData=response.data
                cleanedData = cleanedData.replace(/\/\/.*$/gm, '');
                cleanedData = cleanedData.replace(/^\s*\n*\"|\"\n*\s*$/g, '');
                cleanedData = cleanedData.replace(/\s+/g, ' ');
                cleanedData = cleanedData.replace(/javascript/g,'');
                cleanedData = cleanedData.replace(/\`{3}/g, '');
                cleanedData = cleanedData.replace(/;.*$/, ';')
                try {
                var showJsonData=JSON.parse(cleanedData)
                var raw=0
                showJsonData.forEach(item=>{
                    var column=0
                    Object.keys(item).forEach(key=>{
                        luckysheet.setCellValue(raw,column,item[key])
                        column++
                    })
                    raw++
                })
                } catch (error) {
                    this.$message.error('sorry，AI生成数据时出现错误');
                }

            })
            //console.log(this.need)
            
            //luckysheet.setRangeValue(luckysheet.getRangeJson(false))
                }
                else{
                    this.$message({
                message: '警告哦，输入内容为空！',
                type: 'warning'
                });
                }
            }else{
                this.$message({
                message: '警告哦，表格为空！',
                type: 'warning'
                });
            }
            
        },
        handleBack(){
            luckysheet.undo()
        },
        simpleMap(number){
            var mapSet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
            return mapSet[number]
        }

    }
}
</script>

<style scoped> 
.input-container {
    position: absolute;
    bottom: 80px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(90, 79, 79, 0.5);
    padding: 10px;
    border-radius: 5px;
    z-index: 1000; 
    display: flex; /* 使用Flexbox布局 */
}

.button-container {  
  display: flex;  
  flex-direction: column; /* 使按钮垂直堆叠 */  
  margin-left: 10px; 
  margin-top: 10px; 
  align-items: flex-end;; /* 设置交叉轴对齐方式 */
}



/* input {
    width: 400px;
    height: 80px;
    border: none;
    outline: none;
} */
</style>